package org.ruanjj.longestPalindrome;

public class Solution {
    // 中心扩散法
    public String longestPalindrome(String s) {
        int maxLength = 0;
        if(s.length() < 2){
            return s;
        }
        String res = "";
        for(int i = 0; i < s.length(); i++){
            int oddLength = getLengthAroundCenter(s,i,i);
            int evenLength = getLengthAroundCenter(s,i,i+1);
            int curMaxLength = Math.max(oddLength,evenLength);
            if(maxLength < curMaxLength){
                maxLength = curMaxLength;
                res = s.substring(i-(maxLength-1)/2,i+maxLength/2+1);
            }
        }
        return res;
    }

    private int getLengthAroundCenter(String s, int leftIndex, int rightIndex){
        while(leftIndex > -1 && rightIndex<s.length()){
            if(s.charAt(leftIndex) == s.charAt(rightIndex)){
                leftIndex--;
                rightIndex++;
            }else{
                break;
            }
        }
        return rightIndex-leftIndex-1;
    }

}
